/**
 * 
 */
package com.manolo.event.dispatcher;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import com.manolo.event.HandCardEvent;
import com.manolo.event.GameStartEvent;
import com.manolo.event.listener.CardListener;
import com.manolo.event.listener.GameListener;

/**
 * @author meyer
 *
 */
public class CardDispatcher {

	private static CardDispatcher instance;

	private List<CardListener> externalListeners;
	private List<CardListener> localListeners;

	private CardDispatcher() {
		this.externalListeners = new ArrayList<CardListener>();
		this.localListeners = new ArrayList<CardListener>();
	}

	public void addExternalListener(CardListener listener) {
		this.externalListeners.add(listener);
	}
	
	public void addLocalListener(CardListener listener) {
		this.localListeners.add(listener);
	}

	public void removeExternalListener(CardListener listener) {
		this.externalListeners.remove(listener);
	}
	
	public void removeLocalListener(CardListener listener) {
		this.externalListeners.remove(listener);
	}

	/**
	 * control singleton instance
	 * 
	 * @return
	 */
	public static CardDispatcher getInstance() {
		if (instance == null) {
			instance = new CardDispatcher();
		}
		return instance;
	}
	
	public void dispatchHandCardEvent(HandCardEvent event, DispatchType type) {
		List<CardListener> copyList;
		Iterator<CardListener> listener;
		
		switch (type) {
			case EXTERNAL:
				copyList = new ArrayList<CardListener>(this.externalListeners);
				Collections.copy(copyList, this.externalListeners);
				listener = copyList.iterator();
				while( listener.hasNext() ) {
					((CardListener) listener.next()).handCards(event);
				}
				break;
			case LOCAL:
				copyList = new ArrayList<CardListener>(this.localListeners);
				Collections.copy(copyList, this.localListeners);
				listener = copyList.iterator();
				while( listener.hasNext() ) {
					((CardListener) listener.next()).handCards(event);
				}
				break;
		}
	}
	
}
